package cn.range.androidfileclient;

import java.io.File;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.multipart.FilePart;
import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
import org.apache.commons.httpclient.methods.multipart.Part;
import org.apache.http.HttpStatus;

import cn.range.androidfileclient.R;
import cn.range.service.FileService;

import android.os.Bundle;
import android.os.Environment;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.*;


public class MainActivity extends Activity {

	private EditText nameText;
	
	public static final String ACTION_URL = "http://10.206.17.80:8080/";
	public static final String DEFAULT_FILE_NAME = "xmldata.xml";
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        nameText = (EditText)this.findViewById(R.id.filename);
        
        Button button = (Button) this.findViewById(R.id.button1);
        button.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				//Log.e("HEHE", e.toString());
				String name = nameText.getText().toString();
				
				save(v);
				
			}

			private void save(View v) {
				// TODO Auto-generated method stub
				upload();
			}
		});
}
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }

    public void upload(){
    	Toast.makeText(this, "Starting uploading..", Toast.LENGTH_LONG).show();
    	String targetUrl = ACTION_URL;
    	
    	File targetFile = new File(DEFAULT_FILE_NAME);
    	
    	PostMethod filePost = new PostMethod(targetUrl);
    	
    	try{
    		byte buffer[] = new byte[1024];
    		Part parts[] = 
    		{		new FilePart(targetFile.getName() + System.currentTimeMillis(), 
    				targetFile)};
    		
    		filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams()));
    		HttpClient client = new HttpClient();
    		client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
    		
    		int status = client.executeMethod(filePost);
    		
    		if(status == HttpStatus.SC_OK){
    			System.out.println("Upload succeeded!");
    		}else{
    			System.out.println("Upload failed!");
    		}
    	}catch(Exception e){
    		
    	}finally{
    		filePost.releaseConnection();
    	}
    	
    }
}
